package ncu.me.musicplayer.player;

import android.content.Context;
import android.media.MediaPlayer;

import java.io.IOException;

/**
 * @Author ye
 * @Date 2020/6/1 20:57
 * @Version 1.0
 */
public class MusicPlayer implements IPlayer {
    MediaPlayer  mPlayer;
    Context mContext;
    OnPlayFinishedListener mListener;
    public MusicPlayer(Context context){
        mContext = context;
        mPlayer = new MediaPlayer();
        mPlayer.setOnCompletionListener(mp -> {
            if (mListener!=null){
                mListener.onFinish();
            }
        });
    }
    @Override
    public void play(String path){
        try {
            mPlayer.reset();
            mPlayer.setDataSource(path);
        } catch (IOException e) {
            e.printStackTrace();
        }
        play();
    }
    public void play(){
        try {
            mPlayer.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        }
        mPlayer.start();
    }
    @Override
    public void stop() {
        if (mPlayer != null){
            mPlayer.stop();
        }
    }

    @Override
    public void resume() {
        if (!isPlaying()){
            mPlayer.start();
        }
    }

    @Override
    public void pause() {
        if (isPlaying()){
            mPlayer.pause();
        }
    }

    @Override
    public void seek(int pos) {
        mPlayer.seekTo(pos);
    }

    @Override
    public int size() {
        return mPlayer.getDuration();
    }
    @Override
    public int pos() {
        return mPlayer.getCurrentPosition();
    }

    @Override
    public boolean isPlaying() {
        return mPlayer.isPlaying();
    }

    @Override
    public void setOnFinishedListener(OnPlayFinishedListener listener) {
        mPlayer.setOnCompletionListener(mp -> listener.onFinish());
    }
}
